<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
Class Mgpeople extends MY_Model
{
    public function __construct()
    {
        parent::__construct();
    }    
    
    public function dbincentives($number = 0,$offset = 0,$keyword,$label,$manager)
    {
        $limit = $offset ? intval($offset) : '0';
        
        $sql = "SELECT DISTINCT ic.id,ic.title,ic.image,ic.summary,ic.admin_id,ic.active,ic.type,ic.type_sl,ic.province_id,u.username,ic.is_partner FROM incentive_restaurant AS ic LEFT JOIN user AS u ON u.id = ic.admin_id LEFT JOIN incentive_restaurant_key AS ick ON ick.id_incentive = ic.id WHERE 1=1";
        
        if(!in_array($keyword, array(null, ''))){
            $sql .= " AND (ic.`title` LIKE '%".$keyword."%' OR ic.`summary` LIKE '%".$keyword."%' OR ic.`content` LIKE '%".$keyword."%')";
        }
        if(!in_array($label, array(null, ''))){
            $sql .= " AND (ick.id_restaurant = ".$label." OR ic.type_sl = 0)";
        }
        if(!in_array($manager, array(null, ''))){
            $sql .= " AND ic.admin_id = ".$manager;
        }
        $sql .= " ORDER BY ic.id DESC";
        //die($sql);
        $count = $this->db->query($sql)->num_rows();
        if($offset >= $count && $count != 0){
            $this->load->view('template/404',$this->data);
            return false;
        }
        
        $xdata = " LIMIT ".$limit.",".$number." ";
        //Lấy tất cả incentive
        $xs = $this->db->query($sql.$xdata)->result_object();
//        var_dump($xs);die;
        //Duyệt từng incentive lấy restaurant và zone
        foreach($xs AS $key => $value){
                $restaurants = $this->db->query("SELECT r.name FROM restaurant AS r LEFT JOIN incentive_restaurant_key AS irk ON irk.id_restaurant = r.id WHERE irk.id_incentive = ".$value->id)->result_object();
                $xs[$key]->restaurants = $restaurants;
                $zone = $this->db->query("SELECT z.title FROM zone AS z LEFT JOIN incentive_zone_key AS izk ON z.id = izk.id_zone WHERE izk.id_incentive = ".$value->id)->result_object();
                $xs[$key]->zone = $zone;
        }
        return array('data' => $xs, 'count' => $count);
    }
    
    private function remove_null_tags($st){
		$Char 	= '<p> </p>|<p>&nbsp;</p>|<p></p>|<span> </span>|<span>&nbsp;</span>|<span></span>|<div> </div>|<div>&nbsp;</div>|<div></div>';
		$explChar 	= explode("|", $Char);
		return str_replace($explChar, '', $st);
	}
    public function addIncentiveDb($dataAdd)
    {
//        var_dump($dataAdd);
        $post = strip_tags($dataAdd['content'],"<a><br>");
        $title_ascii = $this->get_ascii($dataAdd['title']);
        $data = array(
            'title' => $dataAdd['title'],
            'title_ascii' => $title_ascii,
            'image' => $dataAdd['img'],
            'slide_image' => $dataAdd['img1'],
            'summary' => $dataAdd['summary'],
            'content' => '<div style="font-family: OpenSans;">'.str_replace('<br/>', '', nl2br($this->remove_null_tags($post))).'</div>',
            'ecoupon' => $dataAdd['coupon'],
//            'province_id' => $province_apply,
//            'type' => $type,
            'admin_id' => $dataAdd['admin'],
//            'type_sl' => $type_sl,
            'created' => date("Y-m-d H:i:s"),
            'active'	=> $dataAdd['active'],
            //			'is_partner' => $this->getParamInt('is_partner')
        );
        $this->db->insert('incentive_restaurant', $data);
        $id = $this->db->insert_id();
        $this->addIncenRes($id,$dataAdd['restaurant']);
        $this->addIncenZone($id,$dataAdd['zone']);
        return 200;
    }
    
    private function addIncenRes($id,$restaurant,$admin_id)
    {
        foreach($restaurant AS $key=>$value)
        {
            $data = array(
                'id_restaurant' => $value,
                'id_incentive' => $id,
//                'admin_id' => $admin_id,
                'created' => date("Y-m-d H:i:s")
            );
            $this->db->insert('incentive_restaurant_key', $data);
        }    
    }
    
    private function addIncenZone($id,$zone,$admin_id)
    {
        foreach($zone AS $key=>$value)
        {
            $data = array(
                'id_zone' => $value,
                'id_incentive' => $id,
//                'admin_id' => $admin_id,
                'created' => date("Y-m-d H:i:s")
            );
        
            $this->db->insert('incentive_zone_key', $data);
        }
    }
    
    public function dbgetrestaurant()
    {
        $sql = "SELECT id,name FROM restaurant";
        $data = $this->db->query($sql)->result_array();
        return $data;
    }
    
    public function editIncentiveDb($dataEdit)
    {
        $post = strip_tags($dataEdit['content'],"<a><br>");
        $title_ascii = $this->get_ascii($dataEdit['title']);
        $data = array(
            'title' => $dataEdit['title'],
            'title_ascii' => $title_ascii,
            'image' => $dataEdit['img'],
            'slide_image' => $dataEdit['img1'],
            'summary' => $dataEdit['summary'],
            'content' => '<div style="font-family: OpenSans;">'.str_replace('<br/>', '', nl2br($this->remove_null_tags($post))).'</div>',
            'ecoupon' => $dataEdit['coupon'],
//            'province_id' => $province_apply,
//            'type' => $type,
            'admin_id' => $dataEdit['admin'],
//            'type_sl' => $type_sl,
            'created' => date("Y-m-d H:i:s"),
            'active'	=> $dataEdit['active'],
            //			'is_partner' => $this->getParamInt('is_partner')
        );
        if(!in_array($img, array(null, '', '0')))
        {
            $data['image'] = $img;
        }
        if(!in_array($img1, array(null, '', '0')))
        {
            $data['slide_image'] = $img1;
        }        
        
        $this->db->update('incentive_restaurant', $data, "id = '".$dataEdit['id']."'");
        $this->dbeditincentiveskey($dataEdit['id'], $dataEdit['restaurant'], $dataEdit['admin']);
        $this->dbeditzonekey($dataEdit['id'], $dataEdit['zone'], $dataEdit['admin']);
        return 200;
    }
    private function dbeditincentiveskey($id,$restaurant,$admin_id)
    {
        $this->db->delete('incentive_restaurant_key', array('id_incentive' => $id));
        foreach($restaurant AS $key=>$value)
        {
            $data = array(
                'id_restaurant' => $value,
                'id_incentive' => $id,
                'admin_id' => $admin_id,
                'created' => date("Y-m-d H:i:s")
            );
        
            $this->db->insert('incentive_restaurant_key', $data);
        }
    }
    
    private function dbeditzonekey($id,$zone,$admin_id)
    {
        $this->db->delete('incentive_zone_key', array('id_incentive' => $id));
        foreach($zone AS $key=>$value)
        {
            $data = array(
                'id_zone' => $value,
                'id_incentive' => $id,
                'admin_id' => $admin_id,
                'created' => date("Y-m-d H:i:s")
            );
            
            $this->db->insert('incentive_zone_key', $data);
        }
    }
    public function dbgetinfoincentives($id)
    {
        $query = $this->db->query('SELECT * FROM incentive_restaurant WHERE id = "'.$id.'"');
        if($query->num_rows() > 0)
        {
            $data = $query->row_array();
            $data['id_restaurant'] = $this->db->query('SELECT id_restaurant AS id FROM incentive_restaurant_key WHERE id_incentive = '.$id)->result_array();
            $data['id_zone'] = $this->db->query('SELECT id_zone AS id FROM incentive_zone_key WHERE id_incentive = '.$id)->result_array();
            return $data;
        }else{
            redirect('manage/g-people/incentives'); 
        }
    }    
    
    public function dbactiveincentives($id)
    {
        $de_active = array('active' => 0);
        $active = array('active' => 1);
        $data = $this->db->query("SELECT active FROM incentive_restaurant WHERE id = '".$id."'")->row_array();
        if($data['active'] == 0)
        {
            $this->db->update('incentive_restaurant', $active, "id = '".$id."'");
        }else{
            $this->db->update('incentive_restaurant', $de_active, "id = '".$id."'");
        }
        return 200;
    }
    
    public function dbdeleteincentives($id)
    {
        $img=$this->db->query("SELECT image,slide_image FROM incentive_restaurant WHERE id = '".$id."'")->row_array();
        foreach($img AS $value)
        {
            @unlink(PROJECT_PATH.'/data/'.$value);
        }
        
        $this->db->delete('incentive_restaurant', array('id' => $id));
        $this->db->delete('incentive_restaurant_key', array('id_incentive' => $id));
        $this->db->delete('incentive_zone_key', array('id_incentive' => $id));
        return 200;
    }
    
    public function selecteCoupon()
    {
        $sql = "SELECT id,title AS name FROM ecoupon";
        $data = $this->db->query($sql)->result_array();
        return $data;
    }
    
    public function listProvince()
    {
        $sql = "SELECT provinceid AS id,name FROM vn_province";
        $data = $this->db->query($sql)->result_array();
        return $data;
    }
    
    public function dbgetmanager()
    {
        $sql = "SELECT id,username,fullname FROM `user` WHERE level = 6";
        $data = $this->db->query($sql)->result_array();
        return $data;
    }
    
    public function getTotalZone()
    {
        return $this->db->query("SELECT id FROM zone")->num_rows();
    }
}
